<template>
  <div class="shop-car">
    <template v-if="isLogin">
      <!--  头部  -->
      <div class="header">
        <p class="active">购物车({{ shopCarModule.shopCarList.length }})</p>
        <!--  点击更多弹出的框  -->
        <van-popover v-if="!isManageMode" placement="bottom-end" v-model:show="showPopover" theme="dark"
                     :actions="moreActions"
                     @select="handleMoreSelect">
          <template #reference>
            <p>更多</p>
          </template>
        </van-popover>
        <p v-else @click="isManageMode = false">退出管理</p>
      </div>
      <!--  商品信息  -->
      <div class="car-main">
        <ZJScrollView ref="carMainScrollRef" :wrapperConfig="carMainScrollConfig">
          <template #content>
            <van-checkbox-group v-model="checkedShopCarItems" @change="handleSingleCheckChange">
              <template v-for="item in shopCarModule.shopCarList" :key="item.id">
                <van-swipe-cell>
                  <div class="main-item" @click="handleItemClick(item)">
                    <van-checkbox :name="item" @click.stop/>
                    <div class="item-img">
                      <img :src="item.subImages" alt="goods_img">
                    </div>
                    <div class="item-info">
                      <p class="info-name">{{ item.name }}</p>
                      <p class="info-choose">{{ Object.values(item.productSpecs).join(" ") }}</p>
                      <div class="price-number">
                        <p class="price">
                          <span>￥</span>
                          <span>{{ item.price }}</span>
                        </p>
                        <div class="number">
                    <span
                        v-show="!item.isStepperMode"
                        class="word"
                        @click.stop="item.isStepperMode = true">
                      ×{{ item.quantity }}
                    </span>
                          <van-stepper @click.stop v-show="item.isStepperMode" v-model="item.quantity"
                                       @change="handleStepperChange(item)"/>
                        </div>
                      </div>
                    </div>
                  </div>
                  <template #right>
                    <van-button square text="删除" type="danger" class="delete-button"
                                @click="handleDelete('single', item)"/>
                  </template>
                </van-swipe-cell>
              </template>
            </van-checkbox-group>
            <template v-if="!shopCarModule.shopCarList.length">
              <van-empty description="快去选购心爱之物吧~"/>
            </template>
          </template>
        </ZJScrollView>
      </div>
      <!--  结算  -->
      <van-submit-bar class="shop-line" :price="totalPrice * 100" :button-text="submitBarBtnTxt" @submit="onSubmit">
        <van-checkbox v-model="allChecked" @click="handleAllCheckChange()">全选</van-checkbox>
      </van-submit-bar>
      <!--  结算页面  -->
      <router-view/>
    </template>
    <template v-else>
      <van-empty description="暂未登录">
        <van-button type="primary" round>立即登录</van-button>
      </van-empty>
    </template>
  </div>
</template>

<script setup lang="ts">
import {computed, nextTick, onActivated, ref, watch, watchEffect} from "vue";
import ZJScrollView from "@/components/ZJScrollView/ZJScrollView.vue";
import useShopCarModule from "@/store/shopCarModule";
import {carMainScrollConfig} from './config'
import {IShopCarItem} from "@/store/shopCarModule/types";
import {useRoute, useRouter} from "vue-router";
import {Dialog, PopoverAction, Toast} from "vant";
import {checkIsLogin} from "@/utils";

const route = useRoute()
const router = useRouter()
const carMainScrollRef = ref<InstanceType<typeof ZJScrollView>>()
const isLogin = ref(false)

const shopCarModule = useShopCarModule()
// 默认的计步器
const showPopover = ref(false)
const moreActions = [
  {
    text: "分享"
  },
  {
    text: "搜索"
  }, {
    text: "管理"
  }
]

const checkedShopCarItems = ref()
const isManageMode = ref(false)
const submitBarBtnTxt = ref("立即购买")
// 计算总价格
const totalPrice = computed(() => {
  if (checkedShopCarItems.value) {
    return checkedShopCarItems.value.reduce((prev: number, item: any) => {
      return prev + item.price * item.quantity
    }, 0)
  } else {
    return 0
  }
})
// 单个复选框发生改变时
const handleSingleCheckChange = () => {
  // 如果列表的长度等于选中的长度说明现在已经全部被选中了
  allChecked.value = checkedShopCarItems.value.length === shopCarModule.shopCarList.length;
}
// 全选的改变
const allChecked = ref(false)
const handleAllCheckChange = () => {
  if (allChecked.value) {
    checkedShopCarItems.value = shopCarModule.shopCarList
  } else {
    checkedShopCarItems.value = []
  }
}
// 处理单个点击
const handleItemClick = (item: IShopCarItem) => {
  router.push('/goods/detail/' + item.productId)
}
// 处理更多按钮的点击
const handleMoreSelect = (action: PopoverAction, index: number) => {
  if (action.text === "管理") {
    isManageMode.value = true
  }
}
// 提交订单按钮
const onSubmit = () => {
  const checkedItems = checkedShopCarItems.value
  if (!checkedItems?.length || !checkedItems) {
    return Toast.fail("请选择商品")
  }
  if (isManageMode.value) { // 批量删除
    handleDelete("multiple")
  } else {
    shopCarModule.saveShopCarDataAction(checkedShopCarItems.value)
    router.push("/shop-car/payment")
  }
}
// 处理步进器
const handleStepperChange = async (item: IShopCarItem) => {
  if (!item.quantity) return
  const {productSpecsId, productId, quantity} = item
  const isSuccess = await shopCarModule.updateShopCarAction({
    data: {
      productTotal: quantity,
      productId,
      productSpecsId
    },
    needNavigate: "/shop-car"
  })
  if (!isSuccess) {
    await shopCarModule.setShopCarAction({
      needNavigate: "shop-car"
    })
    // 刷新列表容器
    refreshScrollWrapper()
  }
}
// 处理删除
const handleDelete = async (type: string, item?: IShopCarItem) => {
  let ids: number[] = []
  if (type === "single") {
    ids.push(item!.id)
  } else {
    ids = checkedShopCarItems.value.map((item: any) => item.id)
  }
  Dialog.confirm({
    title: '提示',
    message:
        '确定要删除选中商品吗？',
  })
      .then(async () => {
        // 实时更新总计价格
        checkedShopCarItems.value = []
        const isSuccess = await shopCarModule.deleteShopCarAction({
          ids
        })
        if (isSuccess) {
          await shopCarModule.setShopCarAction({
            needNavigate: "shop-car"
          })
          refreshScrollWrapper()
        }
      })
      .catch(() => {
      });
}
// 刷新滚动容器
const refreshScrollWrapper = () => {
  nextTick(() => {
    carMainScrollRef.value.bs.refresh()
  })
}
watchEffect(() => {
  if (isManageMode.value) {
    submitBarBtnTxt.value = "批量删除"
  } else {
    submitBarBtnTxt.value = "立即购买"
  }
})
const initData = async () => {
  const toast = Toast.loading("加载中...")
  const isSuccess = await shopCarModule.setShopCarAction({})
  if (isSuccess) { // 请求失败才判断登录状态
    allChecked.value = false
    checkedShopCarItems.value = []
    refreshScrollWrapper()
  } else {
    isLogin.value = checkIsLogin()
  }
  toast.clear()
}
onActivated(async () => {
  await initData()
})
watch(route, async () => {
  if (route.path === "/shop-car") {
    await initData()
  }
})
</script>

<style scoped lang="less">
.shop-car {
  height: 100%;

  .header {
    height: 50px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    padding: 0 8px;
    align-items: center;

    .active {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .car-main {
    padding: 10px;
    height: calc(100% - 100px);
    box-sizing: border-box;
    overflow: hidden;

    .main-item {
      display: flex;
      background-color: #fff;
      border-radius: 8px;
      padding: 10px;
      margin-bottom: 16px;

      .item-img {
        width: 80px;
        height: 80px;
        margin-left: 10px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .item-info {
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        flex: 1;
        margin-left: 10px;

        .info-name {
          font-weight: 600;
          margin-bottom: 8px;
        }

        .info-choose {
          margin-bottom: 8px;
          color: #999;
        }

        .price-number {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 32px;

          .price {
            color: #C81C22;
            font-size: 16px;
            font-weight: 600;
          }

          .number {
            .word {
              padding: 4px 4px;
              border: 1px solid #c1c1c1;
              border-radius: 4px;
            }
          }
        }
      }
    }

    .delete-button {
      height: 100%;
    }
  }

  .shop-line {
    bottom: 50px;
  }
}
</style>
